<?php
namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;

use App\Models\Area;
use App\Models\AreaExtend;
use App\Models\AreaState;
use App\Models\Account\LoginWhite;

use Encore\Admin\Grid;
use Encore\Admin\Form;
use App\Admin\Extra\Search\Html;
use \Illuminate\Support\Facades\Input;
/*  修改的sql
    alter  table tb_area_info change idx id int DEFAULT '0' COMMENT 'ID';
    alter  table tb_game_version change idx id int DEFAULT '0' COMMENT 'ID';
*/
class AreaController extends Controller
{
    public function anyAreaSelectApi(){
    }

    public function index()
    {

        return Admin::content(function (Content $content) {
            $content->header('server list');
            $content->description('server baseic config. this is very important,it is related that is the game server running normally, Please dont change at will. Please contact the area manager if you want to change an area info ');

            $content->row(Html::append([
                Html::likeRedirect('name', 'server name', url()->current()),
                Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current()),
            ]));	

            $grid = Admin::grid(Area::class, function(Grid $grid){
                //$grid->model()->where('deleted_at', 0);//

                $grid->actions(function($actions)use(&$row){
                    $row = $actions->row;
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append(Html::button(' SHOW ', '/admin/area/show?id='.$row->id, 'btn-goto btn-xs'));
                    $actions->append(Html::button('edit extend', '/admin/area/edit-extend?id='.$row->id, 'btn-goto btn-xs'));
                    $actions->append(Html::button('EDIT', '/admin/area/edit?id='.$row->id, 'btn-goto btn-xs'));
                    $actions->append(Html::button('DEL', '/admin/area/api-delete?_id='.$actions->getKey().'&deleted_at=1', 'confirm-ajax btn-danger btn-xs btn-clear'));
                });

                // 第一列显示id字段，并将这一列设置为可排序列
                $grid->id('ID')->sortable();
                $grid->model()->orderBy('id', 'DESC');
                $grid->name('area name');
                $grid->areaId('area id');
                $grid->area_physics('AreaPhysics');
                $grid->ip('ip');
                $grid->mc('mc');
                $grid->roleLimit('roleLimit');
                //$grid->group_area('group');
                $grid->version('version');
                $grid->roleCount('online num')->display(function ($value){
                    $dis_view = "<a href=\"/admin/player/list-account?lastAreaId={$this->areaId}\"><span class=\"badge\">{$value}</span></a>";
                    return $dis_view;
                });
                $grid->state()->display(function($value){
                    switch ($value){
                    case 0:
                        $label_class = "label-default";
                        break;
                    case 1:
                        $label_class = "label-success";
                        break;
                    case -1:
                        $label_class = "label-danger";
                        break;
                    case 2:
                        $label_class = "label-info";
                        break;
                    case 3:
                        $label_class = 'label-warning';
                        break;
                    default:
                        $label_class = "label-info";
                    }
                    $h = '<span id="'.$value.'" class="label '.$label_class.'">'.Area::$area_state_type[$value].'</span>';

                    $h = '<a href="/admin/area/state-list?area='.$this->areaId.'&state='. $value .'">' . $h. '</a>';
                    return $h;
                });
                $grid->keepString('推荐概率');
                $grid->op_state('OperState')->display(function($value) {
                    $const_all = 0xFFFF;
                    $class = "btn-goto-ajax btn-xs ";
                    $save_url = '/admin/area/api-save?_id='.$this->id;
                    // op_state   1:禁止新用户登录  2：开启未成年检测
                    $html = $value & 1 ? Html::button('NewReg', \App\Service\Common::build_url_query( $save_url, ['op_state' => $value & ($const_all - 1)]), $class.' btn-info')
                : Html::button('NewReg', \App\Service\Common::build_url_query($save_url,  ['op_state' => $value | 1 ]), $class.' btn-default');
                    $html .= $value & 2 ? Html::button('UnderAge', \App\Service\Common::build_url_query($save_url, ['op_state' => $value & ($const_all - 2)]), $class.'btn-info')
                : Html::button('UnderAge', \App\Service\Common::build_url_query($save_url,  ['op_state' => $value | 2]), $class.' btn-default');
                    return $html;
                });

                // 服务当前状态
                // $states = [
                //     'on'  => ['value' => 1, 'text' => 'online', 'color' => 'success'],
                //     'off' => ['value' => 0, 'text' => 'down', 'color' => 'default'],
                //     'url' => url()->to("/admin/area/api-send?_id={$row->id}"),
                // ];

                
                // 设置临时跳转路径 行操作使用 TODO
                //$grid->tmpUrl = url()->to("/admin/game-db-conf/api-save?id=".$grid->getKey()->value()."&status=".(''?0:1));
                // $tmp = $grid->state('server state')->switch($states)->display(function($value){
                //     $this->tmpUrl = url()->to("/admin/mail/api-send?_id=".$this->id."&state=".($value?0:1));
                //     return $value;
                // });

                $grid->filter(function ($filter) {

                    // 模糊查询 注意
                    //$filter->where(function($query){
                    //    //$aids = \App\Models\EMail::getAccountByName('', 'playerName');
                    //    //var_dump($aids);exit;
                    //    $query->where('title', 'like', 'T%');
                    //}, '邮件标题', 'title');

                    $filter->like('name', 'area name')->placeholder('');
                    

                    //$filter->disableIdFilter();
                });

            });
        
            $content->row($grid->render());

        });
    }

    public function anyEdit(){
        $id = Input::get('id');

        $one = Area::find($id) ?: new Area;

        $data['one'] = $one;

        
        return Admin::content(function($content) use($data){
		    $content->header('server area edit');
            $grid = Admin::Form(Area::class, function(Form $form)use($data){
                $one = $data['one'];
                //$one->area_list = explode(',', $one->area_list);

                $form->text('name', 'server name')->default($one->name);
                $form->text('areaId', 'area id')->default($one->areaId);
                $form->text('area_physics', 'AreaPhysics')->default($one->area_physics);
                $form->select('state', 'state')->options(Area::$area_state_type)->default($one->state);
                $form->text('keepString', '推荐概率')->default($one->keepString);
                $form->text('ip', 'game ip')->default($one->ip);
                
                $form->text('port', 'port')->default($one->port ?: '0');
                $form->text('group_area', 'group area')->default($one->group_area ?: '0');
                $form->text('version', 'version')->default($one->version ?: '0');
                $form->select('mc', 'mc')->options(Area::$area_mc)->default($one->mc ?: '0');
                $form->text('roleLimit', 'role limit')->default($one->roleLimit ?: '0');
                //$form->textarea('prop', '邮件附件')->default($one->prop);
                $form->hidden('_id', 'id')->default($one->id);

                //$form->html('<script>$("form").on("submit", function(event){if(!$("form").serializeArray().title) return false})</script>', '');

                //$form->tools(function (Form\Tools $tools) {
                //    // 去掉返回按钮
                //    $tools->disableBackButton();
                //    // 去掉跳转列表按钮
                //    $tools->disableListButton();
                //    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                //    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
                //});
                
                //$form->submitted(function(){
                //    return false;
                //});
                $form->saved(function (Form $form) {
                    \Log::debug(json_encode(['data'=>'save click']));
                    admin_toastr('laravel-admin 提示','success');
                    return response('success');
                });

               
                $form->setAction('/admin/area/api-save/');
                $form->method('POST');
                $form->disablePjax();
            });
            $content->row($grid);
        });

    }
    public function anyAdd()
    {
        return $this->anyEdit();
    }

    public function anyEditExtend()
    {
        $id = Input::get('id');

        $one = AreaExtend::find($id) ?: new AreaExtend;
        !$one->id && $one->id = $id;
        $data['one'] = $one;

        $one->open_time = date("Y-m-d H:i:s", $one->open_time);
        return Admin::content(function($content) use($data){
		    $content->header('server area edit');
            $grid = Admin::Form(AreaExtend::class, function(Form $form)use($data){
                $one = $data['one'];
                //$one->area_list = explode(',', $one->area_list);
               
                $form->text('bgsi_ip', 'bgsi ip')->default($one->bgsi_ip);
                $form->text('port', 'port')->default($one->port);
                $form->select('area', 'area')->options(Area::areaSelectData(0))->default($one->area);
                $form->text('name', 'db name')->default($one->name);
                
                $form->text('login_name', 'login name')->default($one->login_name ?: '');
                $form->text('db_password', 'pwd')->default($one->db_password ?: '0');
                $form->datetime('open_time', 'open time')->default($one->open_time?: date("Y-m-d H:i:s"));
                $form->hidden('_id', 'id')->default($one->id);

               
                $form->setAction('/admin/area/api-extend-save/');
                $form->method('POST');
                $form->disablePjax();
            });
            $content->row($grid);
        });       
    }
    public function anyApiSave(){
        $data = Input::all();

        $one = Area::find($data['_id']) ? : new Area();
        \Log::debug("area save api come in", [$one->name, $one->areaId]);
        Area::assignByOut($one, $data);
        
        if (!$one->name || !$one->areaId) {
            echo json_encode(['code' => 444, 'msg' => admin_toastr('area save error!!!','error',['positionClass'=>'toast-center']), 'data' => $data]);
            //return redirect('/admin/area?redirect='.url()->to('/admin/area/').'');
            //redirect('/admin/area/edit?id='.$data['_id']);
            //admin_toastr('area save alert','error');
            return;
        }
        \Log::debug(__METHOD__, ['id' =>$one->id ,'op_state' =>$one->op_state, 'keep'=>$one->keepString]);
        //\Log::debug('###', [$one]);
        $one->save();
        
        Area::clearCache();
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('area save success!!!','success'), 'data' =>$one->areaId]);
        //admin_toastr('area save ','success');
        //return redirect('/admin/area/edit?id='.$data['_id']);
    }

    public function anyApiDelete(){
        $data = Input::all();
        $one = Area::find($data['_id']);
        if ($one){
            $one->delete();
        }

        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('area save success!!!','success'), ]);
    }

    public function anyApiExtendSave(){
        $data = Input::all();

        $one = AreaExtend::find($data['_id']) ? : new AreaExtend();
       
        !$one->id && $one->id = $data['_id'];

        AreaExtend::assignByOut($one, $data);
        \Log::debug("area save api come in", [$one->db_name, $data]);
        if (!$one->bgsi_ip || !$one->area) {
            echo json_encode(['code' => 444, 'msg' => admin_toastr('area extend save error!!!','error',['positionClass'=>'toast-center']), 'data' => $data]);
            //return redirect('/admin/area?redirect='.url()->to('/admin/area/').'');
            //redirect('/admin/area/edit?id='.$data['_id']);
            //admin_toastr('area save alert','error');
            return;
        }
        $one->save();
        
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('area extend save success!!!','success'), 'data' =>$one->areaId]);
        //admin_toastr('area save ','success');
        //return redirect('/admin/area/edit?id='.$data['_id']);
    }

    public function anyShow(){
        $data = Input::all();
        $id = $data['_id'] ?: $data['id'];
        $one = Area::find($id) ? : new Area();
        if (!$one) {
            echo json_encode(['code' => 444, 'msg' => admin_toastr('AREA['.$id.'] data  error!!! not found ' ,'error',['positionClass'=>'toast-center']), 'data' => $data]);
            return ;
        } 
        
        $srv_info = Area::getServerRunInfo($one->areaId);
        return Admin::content(function (Content $content) use($one, $srv_info) {
            $content->header('Server name[' . $one->name . "] - Server Id[". $one->areaId.']');

            if (!$srv_info || !$srv_info['subServer']) {
                $content->description('Not valid server info that get from game center! Please config server http for server manager');
                return;
            }

            $buts = [];
            $buts[] = Html::button('强制关闭' , \App\Service\Common::build_url_query('/admin/area/api-server', ['area' => $one->areaId, 'op' => 1]), 'btn-goto-ajax btn-large btn-danger');
            $buts[] = Html::button('强制启动' , \App\Service\Common::build_url_query('/admin/area/api-server', ['area' => $one->areaId, 'op' => 2]), 'btn-goto-ajax btn-large btn-success');
            $content->row(Html::append($buts));
            foreach ($srv_info['subServer'] as $obj) {
                $buts = [];
                $color = $obj['count'] ? 'btn-success' : 'btn-danger';
                $buts[] = Html::button($obj['name'] , '', 'btn-goto btn-large '.$color);
                $buts[] = Html::button($obj['count'], '', 'btn-goto btn-large '.$color);
               
                $content->row(Html::append($buts));
            }
            
        });
    }

    public function apiServerRestart() {
        $area = Input::get('area',0);
        $op   = Input::get('op', 1);

        $url = Area::getServerRestartUrl($area, $op);

        \Log::info('[GAME_SERVER_RESTART]AREA['.$area.']', ['op' => $op, $url]);
        \App\Third\Curl::request($url, [], 'get');
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('operator server success!!!','success'), 'data' =>$area]);
    }

    //================== 预登陆白名单

    public function anyLoginWhite() {
        return Admin::content(function (Content $content) {
            $content->header('Server login white list manager!');
            $content->description('server baseic config. this is very important,it is related that is the game server running normally, Please dont change at will. Please contact the area manager if you want to change an area info ');

            $content->row(Html::append([
                Html::likeRedirect('account', 'Account', url()->current()),
                Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current()),
            ]));	

            $grid = Admin::grid(LoginWhite::class, function(Grid $grid){
                //$grid->model()->where('deleted_at', 0);//

                $grid->actions(function($actions)use(&$row){
                    $row = $actions->row;
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append(Html::button($row->state ? 'Close' : 'Open', '/admin/area/api-login-white-save?id='.$row->id. "&state=".($row->state?0:1), 'btn-goto btn-goto-ajax btn-xs'.($row->state?' btn-danger':' btn-info') ));
                    $actions->append(' ');
                    $actions->append(Html::button('EDIT', '/admin/area/edit-login-white?id='.$row->id, 'btn-goto btn-xs'));
                    $actions->append(' ');
                    $actions->append(Html::button('DEL', '/admin/area/api-login-white-delete?_id='.$actions->getKey().'&deleted_at=1', 'confirm-ajax btn-danger btn-xs btn-clear'));
                });

                $state_options = LoginWhite::stateOptions();
                // 第一列显示id字段，并将这一列设置为可排序列
                $grid->id('ID')->sortable();
                $grid->account('Account')->display(function($value) {
                    return '<a href="'.url('admin/player/show?accountId='). $value .'">'.$value.'</a>';
                });
                $grid->state('State')->display(function ($value) use ($state_options) {
                    return $state_options[$value] ?: 'Off';
                });
                $grid->create_time('Create Time');
                
                $grid->disableCreateButton();

                $grid->tools(function ($tools)use($artworkid) {
                    $tools->append(Html::button('new', '/admin/area/edit-login-white', 'btn-goto btn-sm btn-success ', 'float:right;'));
    
                });
                $grid->filter(function ($filter) {

                    $filter->like('account', 'Account')->placeholder('');
                    $filter->equal('state', 'State')->select(LoginWhite::stateOptions());

                    //$filter->disableIdFilter();
                });

            });
        
            $content->row($grid->render());

        });
    }

    public function anyEditLoginWhite()
    {
        $id = Input::get('id');
        $clone = Input::get('clone');

        $one = LoginWhite::find($id) ?: new LoginWhite;
        

        $data['one'] = $one;
        $data['clone'] = $clone;
        

        
        return Admin::content(function($content) use($data){
		    $content->header('Login White Edit');
            $grid = Admin::Form(LoginWhite::class, function(Form $form)use($data){
                $one = $data['one'];
                //$one->area_list = explode(',', $one->area_list);
                // $form->html('aaaaaaaaaaaaaa');
                $form->text('account', 'Account')->default($one->account);
                
                
                $form->select('state', 'State')->options(LoginWhite::stateOptions())->default($one->id ? $one->state: 1);
    
                                
                if (!$data['clone']) {
                    $form->hidden('_id', 'id')->default($one->id);
                }

                $form->saved(function (Form $form) {
                    \Log::debug(json_encode(['data'=>'save click']));
                    admin_toastr('laravel-admin ','success');
                    return response('success');
                });
                
                $form->disablePjax();
                $form->setAction('/admin/area/api-login-white-save/');

            });
            $content->row($grid);
        });       
    }

    public function anySaveLoginWhite()
    {
        $data = Input::all();
        $id = $data['id']?: $data['_id'];

        $one = LoginWhite::find($id) ? : new LoginWhite();
        $one->account = $data['account'] ?: $one->account;
        $one->state = isset($data['state']) ? $data['state']: $one->state;

        if (!$one->account) {
            echo json_encode(['code' => -404,'status'=>true, 'msg' => admin_toastr('Login White param error !!!','error'), 'data' =>$data]);
            return;
        }

        if (!$one->id && $one->findByAccount($one->account)) {
            echo json_encode(['code' => -403,'status'=>true, 'msg' => admin_toastr('Login White exist error !!!','error'), 'data' =>$one->account]);
            return ;
        }
        $one->save();
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('Login White save success!!!','success'), 'data' =>$one->account]);
    }

    //================== 服务器列表状态
    public function anyAreaStateList(){
        
        // Input::set('area', Input::get('area', 0));

        return Admin::content(function (Content $content) {
            $content->header('Area state manager!');
            $content->description('server baseic config. this is very important,it is related that is the game server running normally, Please dont change at will. Please contact the area manager if you want to change an area info ');

            $content->row(Html::append([
                Html::likeRedirect('account', 'Account', url()->current()),
                Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current()),
            ]));	
            
            $use_data = Input::all();
            $grid = Admin::grid(AreaState::class, function(Grid $grid) use($use_data){
                //$grid->model()->where('deleted_at', 0);//

                $grid->actions(function($actions)use(&$row){
                    $row = $actions->row;
                    $actions->disableEdit();
                    $actions->disableDelete();
                   
                    $actions->append(Html::button('EDIT', '/admin/area/edit-state?id='.$row->id, 'btn-goto btn-xs'));
                    $actions->append(' ');
                    $actions->append(Html::button('DEL', '/admin/area/api-state-delete?_id='.$actions->getKey().'&deleted_at=1', 'confirm-ajax btn-danger btn-xs btn-clear'));
                });

                $state_options = LoginWhite::stateOptions();
                // 第一列显示id字段，并将这一列设置为可排序列
                $grid->id('Id')->sortable();
                $grid->alias('AliasName')->display(function($value) {
                    return '<a href="'.url('admin/player/show?accountId='). $value .'">'.$value.'</a>';
                });
                // $grid->state('State')->display(function ($value) use ($use_data) {
                //     $btn_class = '';
                //     if ($use_data['state'] == $value && $use_data['area']) {
                //         $btn_class = 'btn-success';
                //     }
                //     return '<span class="btn '.$btn_class.'">' . $value . '</span>';
                // });
                $grid->state()->display(function($value){
                    switch ($value){
                    case 0:
                        $label_class = "label-default";
                        break;
                    case 1:
                        $label_class = "label-success";
                        break;
                    case -1:
                        $label_class = "label-danger";
                        break;
                    case 2:
                        $label_class = "label-info";
                        break;
                    case 3:
                        $label_class = 'label-warning';
                        break;
                    default:
                        $label_class = "label-info";
                    }
                    $h = '<span id="'.$value.'" class="label '.$label_class.'">'.Area::$area_state_type[$value].'</span>';

                    $h = '<a href="/admin/area/state-list?area='.$this->areaId.'&state='. $value .'">' . $h. '</a>';
                    return $h;
                });
                $grid->state_label('StateLabel')->display(function ($value) use ($state_options) {
                    return $value;
                });
                $grid->state_style('StateStyle')->display(function ($value) use ($state_options) {
                    return $value;
                });

                $grid->state_mark('StateMark')->display(function ($value) use ($state_options) {
                    return $value;
                });


                $grid->disableCreateButton();
                $grid->tools(function ($tools)use($artworkid) {
                    $tools->append(Html::button('CLONE', '/admin/area/api-state-clone?area='. Input::get('area'), 'confirm-ajax btn-sm btn-warning ', ''));
                    $tools->append(Html::button('new', '/admin/area/edit-state?area='. Input::get('area'), 'btn-goto btn-sm btn-success ', 'float:right;'));
    
                });
                $grid->filter(function ($filter) {

                    $filter->like('account', 'Account')->placeholder('');
                    $filter->equal('state', 'State')->select(LoginWhite::stateOptions());

                    //$filter->disableIdFilter();
                });

            });
        
            $content->row($grid->render());

        });
    }

    public function anyEditState()
    {
        $id = Input::get('id');
        $clone = Input::get('clone');

        $one = AreaState::find($id) ?: new AreaState;
        

        $data['one'] = $one;
        $data['clone'] = $clone;
        

        
        return Admin::content(function($content) use($data){
		    $content->header('Login White Edit');
            $grid = Admin::Form(AreaState::class, function(Form $form)use($data){
                $one = $data['one'];
                //$one->area_list = explode(',', $one->area_list);
                // $form->html('aaaaaaaaaaaaaa');
                
                $form->select('area', 'area')->options(Area::areaSelectData(0))->default($one->area ?: Input::get('area'));
                $form->select('state', 'state')->options(Area::$area_state_type)->default($one->state);
                $form->text('alias', 'Alias')->default($one->alias);
                // $form->text('state_label', 'label')->default($one->state_label);
                $form->text('state_style', 'StateStyle')->default($one->state_style);
                $form->text('state_mark', 'StateMark')->default($one->state_mark);
                $form->hidden('id', 'id')->default($one->id);
                $form->hidden('_id', 'id')->default($one->id);
                $form->saved(function (Form $form) {
                    \Log::debug(json_encode(['data'=>'save click']));
                    admin_toastr('laravel-admin ','success');
                    return response('success');
                });

                $form->disablePjax();
                $form->setAction('/admin/area/api-state-save/');

            });
            $content->row($grid);
        });       
    }

    public function anySaveState()
    {
        $data = Input::all();
        $id = $data['id']?: $data['_id'];

        $one = AreaState::find($id) ? : new AreaState();
        $one->id = $id;
        $one->alias = $data['alias'];
        $one->area = $data['area'];
        $one->state = $data['state'];
        $one->state_label = $data['state_label'];
        $one->state_style = $data['state_style'];
        $one->state_mark = $data['state_mark'];

        $one->save();
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('Area State save success!!!','success'), 'data' =>$one->account]);
    }

    public function anyCloneState()
    {
        $area = Input::get('area', 0);
        if (empty ($area)) {
            echo json_encode( ['code' => -444,'status'=>true, 'msg' => admin_toastr('Area State clone not valid area choice error!!!','error'), 'data' =>[] ] );
            return;
        }
        $find = new AreaState;
        $count = $find->getCount($area);
        if ($count) {
            echo json_encode( ['code' => -444,'status'=>true, 'msg' => admin_toastr('Area State clone repeat error!!!','error'), 'data' =>[] ] );
            return;
        }

        $find->cloneStateDefault($area);

        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('Area State clone success!!!','success'), 'data' =>$one->account]);
    }

    public function anyApiStateDelete(){
        $data = Input::all();
        $one = AreaState::find($data['_id']?:$data['id']);
        if ($one){
            $one->delete();
        }

        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('area save success!!!','success'), ]);
    }
}

